package com.zhouhailin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhouhailin.domain.LoginUser;
import com.zhouhailin.entity.User;
import com.zhouhailin.mapper.UserMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 自定义实现：UserDetailsService接口
 *
 * @author: zhouhailin
 * @Date : 2024/2/7
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        // 1、基于数据查询用户信息
        // 根据用户名查询用户信息
        // 构建查询条件语句
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, userName);
        User user = userMapper.selectOne(queryWrapper);
        // 如果查询不到数据就通过抛出异常来给出提示
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户名或密码错误！");
        }

        // TODO 根据用户查询权限信息 添加到LoginUser中

        // 将User封装成UserDetails对象返回
        return new LoginUser(user);
    }
}
